﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using U9API.Pub;

namespace U9API
{
    /// <summary>
    /// 权限拦截
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class ValidateFilterAttribute : ActionFilterAttribute
    {
        WebCache.ICacheStorage cache = WebCache.CacheFactory.CreateCacheFactory();
        string GetKey(String orgcode,String primarykey,
           String controllerName)
        {
            return controllerName + "_" + orgcode + "_" + primarykey;
        }
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            base.OnResultExecuted(filterContext);
            String orgcode = filterContext.HttpContext.Request["orgcode"].ObjToString();
            String primarykey = filterContext.HttpContext.Request["primarykey"].ObjToString();
            String controllerName = filterContext.RouteData.Values["controller"].ObjToString();
            String key = GetKey(orgcode, primarykey, controllerName);
            cache.Remove(key);
        }
        /// <summary>
        /// 并发处理
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //权限拦截是否忽略 
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            String orgcode = filterContext.HttpContext.Request["orgcode"].ObjToString();
            String primarykey = filterContext.HttpContext.Request["primarykey"].ObjToString();
            String controllerName = filterContext.RouteData.Values["controller"].ObjToString();
            //String data=filterContext.HttpContext.Request["data"].ObjToString();
            String operation=filterContext.HttpContext.Request["operation"].ObjToString().Trim();

            String data = "";// HttpUtility.HtmlEncode(filterContext.HttpContext.Request["data"]).ObjToString(); 
            try
            {
                data = filterContext.HttpContext.Request["data"].ObjToString();
            }
            catch (HttpRequestValidationException ex)
            {
                Pub.WriteLog.WriteLine("传入参数数据非法！" + ex.Message);
                JsonModel.APIResponse result = new JsonModel.APIResponse();
                result.code = "001";
                result.data = null;
                result.successful = 1;
                result.message = "传入参数数据非法！不能输入< $特殊字符，请检查数据";
                filterContext.Result = new ErrorResult(result);
                return;
            }
            if(String.IsNullOrEmpty(orgcode)||String.IsNullOrEmpty(primarykey)
                || String.IsNullOrEmpty(data) || String.IsNullOrEmpty(operation) || (operation != "2"&& operation != "1" && operation != "0"))
            {
                JsonModel.APIResponse result = new JsonModel.APIResponse();
                result.code = "001";
                result.data = null;
                result.successful = 1;
                result.message = "传入参数非法！";
                if (String.IsNullOrEmpty(orgcode))
                {
                    result.message += "请检查传入的参数（账套号）是否有空值！";
                }
                else if (String.IsNullOrEmpty(primarykey))
                {
                    result.message += "请检查传入的参数（主键）是否有空值！";
                }
                else if (String.IsNullOrEmpty(operation))
                {
                    result.message += "请检查传入的参数（操作）是否有空值！";
                }
                else if (String.IsNullOrEmpty(data) )
                {
                    result.message += "请检查传入的参数（数据）是否有空值！";
                }
                else
                {
                    result.message += "参数（操作）必须为0，1或2！";
                }
                filterContext.Result=new ErrorResult(result);
                //Pub.WriteLog.WriteLine("ValidateFilterAttribute", "Create", filterContext.Result.ToString());
                return;
            }
            String key = GetKey(orgcode, primarykey, controllerName);
            if (cache.Get(key) != null)
            {
                JsonModel.APIResponse result = new JsonModel.APIResponse();
                result.code = "001";
                result.data = null;
                result.successful = 1;
                result.message = "单据现在有操作正在处理中,请稍后再试！" + data;
                        filterContext.Result=new ErrorResult(result);
                        ////Pub.WriteLog.WriteLine("ValidateFilterAttribute", "Create", filterContext.Result.ToString());
                return;
            }
            else
            {
                cache.Insert(key, data,TimeSpan.FromMinutes(10));
            }
            base.OnActionExecuting(filterContext);
        }
    }
}